//

package main

import (
	"errors"
	"fmt"

	"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

type SimpleContract struct {
	contractapi.Contract
}

// create
func (sc *SimpleContract) create(ctx contractapi.TransactionContextInterface, key string, value string) error {
	//check if existed
	exist, err := ctx.GetStub().GetState(key)
	if err != nil {
		return errors.New("unable to interact with world state!")
	}
	if exist != nil {
		return fmt.Errorf("cannot create world state pair with key:%s, already exists", key)
	}
	//
	err = ctx.GetStub().PutState(key, []byte(value))
	if err != nil {
		return errors.New("unable to interact with world state!")
	}
	return nil
}
//update
func (sc *SimpleContract) update(ctx contractapi.TransactionContextInterface, key string, value string) error {
	//check if existed
	exist, err := ctx.GetStub().GetState(key)
	if err != nil{
		return errors.New("unable to interact with world state")
	}
	if exist == nil{
		return fmt.Errorf("world state :%s does not exist", key)
	}

	err = ctx.GetStub().PutState(key, []byte(value))
	if err != nil {
		return errors.New("unable to interact with world state!")
	}
	return nil
}
//read
func (sc *SimpleContract) read(ctx contractapi.TransactionContextInterface, key string) (string, error) {
	exist, err := ctx.GetStub().GetState(key)
	if err != nil {
		return "", errors.New("unable to interact with world state!")
	}
	if exist == nil {
		return "", fmt.Errorf("world state: %s does not exist", key)
	}

	return string(exist), nil
}

//main
func main(){
	//instance
	simpleContract := new(SimpleContract)
	cc, err := contractapi.NewChaincode(simpleContract)
	if err != nil {
		panic(err.Error())
	}
	//start
	if err := cc.Start();err != nil {
		panic(err.Error())
	}
}

